package ltd.jdsoft.cute.perm.manager;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.auth0.jwt.interfaces.DecodedJWT;

import ltd.jdsoft.cute.jwt.utils.JWTUtils;
import ltd.jdsoft.cute.perm.jwt.PermJwtParams;
import ltd.jdsoft.cute.perm.model.User;
import ltd.jdsoft.cute.perm.service.UserService;

@Component
public class UserManager {

  private static Logger logger = LoggerFactory.getLogger(UserManager.class);
  @Autowired
  private UserService userService;

  /**
   * 根据用户名、密码认证
   * 
   * @param name
   * @return
   */
  public User authentication(String loginName, String password) {
    User user = userService.getByLoginName(loginName);
    if (user == null) {
      return null;
    }

    if (user.getPassword().equals(DigestUtils.md2Hex(password))) {
      return user;
    }

    return null;
  }

  /**
   * 通过token认证
   * 
   * @param token
   * @return
   */
  public User authentication(String token) {
    try {
      // 验证token
      DecodedJWT decodeJWT = JWTUtils.verifier.verify(token);
      long userId = decodeJWT.getClaim(PermJwtParams.UID).asLong();

      return userService.getById(userId);
    } catch (Exception e) {
      logger.error("authentication by token error", e);

      return null;
    }
  }
}
